package com.m7788.util;

import android.annotation.TargetApi;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.view.View;
import android.view.animation.Interpolator;

/**
 * 动画插值坐标获取
 * @author gxchen
 */
public class MoveDistanceGetRunnable implements Runnable {
	private float from, to;
	private int mDuration;
	private Interpolator mInterpolator;
	private boolean mContinueRunning = true;
	private long mStartTime = -1;
	private float mCurrentLoc = -1;
	private View mMoveView;
	private OnMoveListener mOnMoveListener;
	private int mTriggerId = -1;

	public interface OnMoveListener {
		public void getCurLoc(float curLoc);

		public void onMoveFinished(int triggerId);
	}

	private void postOnAnimation(View view, Runnable runnable) {
		if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
			postOnAnimationOfApi16(view, runnable);
		} else {
			view.postDelayed(runnable, 16);
		}
	}

	@TargetApi(16)
	private void postOnAnimationOfApi16(View view, Runnable runnable) {
		 view.postOnAnimation(runnable);
	}

	public MoveDistanceGetRunnable(float from, float to, int duration,
			Interpolator mInterpolator, View view, OnMoveListener onMoveListener,int triggerId) {
		super();
		this.from = from;
		this.to = to;
		this.mDuration = duration;
		this.mInterpolator = mInterpolator;
		this.mMoveView = view;
		this.mOnMoveListener = onMoveListener;
		this.mTriggerId = triggerId;
	}

	@Override
	public void run() {
		if (mStartTime == -1) {
			mStartTime = System.currentTimeMillis();
		} else {
			/**
			 * We do do all calculations in long to reduce software float
			 * calculations. We use 1000 as it gives us good accuracy and small
			 * rounding errors
			 */
			long normalizedTime = (1000 * (System.currentTimeMillis() - mStartTime))
					/ mDuration;
			normalizedTime = Math.max(Math.min(normalizedTime, 1000), 0);

			final float deltaY = (from - to)
					* mInterpolator.getInterpolation(normalizedTime / 1000f);
			mCurrentLoc = from - deltaY;
			if(mOnMoveListener!=null){
				mOnMoveListener.getCurLoc(mCurrentLoc);
			}
		}

		// If we're not at the target Y, keep going...
		if (mContinueRunning && to != mCurrentLoc) {
			postOnAnimation(mMoveView, this);
		}else if(mOnMoveListener!=null){
			mOnMoveListener.onMoveFinished(mTriggerId);
		}
	}

	public void stopAnim() {
		mContinueRunning = false;
		mMoveView.removeCallbacks(this);
	}

}
